#include "ApplicationLogic.h"

#include "NetworkModel.h"

#include "HttpServer.h"
#include "PhoneBookServlet.h"

#include <QNetworkSession>
#include <QNetworkAddressEntry>

ApplicationLogic::ApplicationLogic(QObject *parent)
    : QObject(parent)
    , m_networkModel(new NetworkModel(this))
    , m_session (NULL)
{


}

ApplicationLogic::~ApplicationLogic()
{

}

QObject* ApplicationLogic::networkModel() const
{
    return m_networkModel;
}

void ApplicationLogic::setNetworkConfigurationRow(int row)
{
    // Destroy old session if neccessary;
    if (m_session != NULL) {
        m_session->close();
        m_session = NULL;
    }

    Q_ASSERT (m_session == NULL);

    QNetworkConfiguration configuration(m_networkModel->configurationForRow(row));

    m_session = new QNetworkSession(configuration, NULL);
    m_session->open();
    m_session->waitForOpened(-1);

    HttpServer* server = new HttpServer(NULL);

    PhoneBookServlet* phone_book_servlet = new PhoneBookServlet(server);
    server->addServlet("/phonebook", phone_book_servlet);

    server->setPort(8080);
    server->setEnabled(true);

    emit ipChanged();
}

QString ApplicationLogic::ip() const
{
    QString visible_ip;
    foreach (QNetworkAddressEntry entry, m_session->interface().addressEntries()) {
        visible_ip.append(entry.ip().toString());
        visible_ip.append('\n');
    }
    return visible_ip;
}





